<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="rules"
    label-width="100px"
    style="padding: 20px 40px"
  >
    <el-form-item label="所属项目" prop="projectId" v-if="!isEdit">
      <el-select v-model="formData.projectId" placeholder="请选择所属项目" style="width: 100%">
        <el-option
          v-for="item in projectList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="章节名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入章节名称" />
    </el-form-item>
    <el-form-item label="排序号" prop="order">
      <el-input-number v-model="formData.order" :min="1" style="width: 100%" />
    </el-form-item>
    <el-form-item label="标题对齐">
      <el-radio-group v-model="formData.config.titleAlign">
        <el-radio-button label="center">居中</el-radio-button>
        <el-radio-button label="left">左对齐</el-radio-button>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="章节描述" prop="description">
      <el-input
        v-model="formData.description"
        type="textarea"
        rows="3"
        placeholder="请输入章节描述"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleConfirm">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, defineProps, watch, computed } from 'vue'
import { useProjectStore } from '@/stores/project'

const projectStore = useProjectStore()
const projectList = computed(() => projectStore.getProjects)

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['close'])

const formRef = ref(null)
const formData = ref({
  projectId: '',
  name: '',
  order: 1,
  description: '',
  config: { titleAlign: 'center' }
})

const rules = {
  projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  name: [{ required: true, message: '请输入章节名称', trigger: 'blur' }],
  order: [{ required: true, message: '请输入排序号', trigger: 'blur' }]
}

// 确认提交
const handleConfirm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      emit('close', formData.value)
    }
  })
}

// 取消
const handleCancel = () => {
  emit('close')
}

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (props.isEdit && newVal) {
      formData.value = {
        projectId: newVal.projectId || '',
        name: newVal.name || '',
        order: newVal.order || 1,
        description: newVal.description || '',
        config: {
          titleAlign: newVal.config?.titleAlign || 'center'
        }
      }
    }
  },
  { immediate: true }
)
</script> 